import datetime
import itchat
import time
from apscheduler.schedulers.blocking import BlockingScheduler
# from apscheduler.schedulers.background import BackgroundScheduler


from getweather import *
from getword import *
from setting import *
from utils.utils import generate_all_msg, get_birthday_timestamp, cal_days, send_email
from wechat import Wechat


IS_WECHAT = False
IS_EMAIL = True

def scheduler():
    # 定时任务
    scheduler = BlockingScheduler(timezone='Asia/Shanghai')
    # 每天规定时间发送
    alarm_time = friend_dict['alarm_time'].strip()

    # 设置默认时间
    hour = 8
    minute = 0
    if alarm_time != '':
        list = alarm_time.split(':')
        hour = int(list[0])
        minute = int(list[1])
    # 启动定时器
    scheduler.add_job(start_info, 'cron', hour=hour, minute=minute)
    # 每隔60秒发送一条数据用于测试。
    # scheduler.add_job(start_info, 'interval', seconds=60)
    scheduler.start()


# 每次定时循环的任务
def start_info():
    # 获取setting中信息
    city_name = friend_dict.get('city_name')
    wechat_name = friend_dict['wechat_name']
    # 时间转化为时间戳
    start_date = time.mktime(time.strptime(friend_dict.get('start_date'), '%Y-%m-%d'))
    love_date = time.mktime(time.strptime(friend_dict.get('love_date'), '%Y-%m-%d'))
    wife_birthday_stamp, is_today_wife = get_birthday_timestamp(friend_dict.get('wife_birthday'))
    husband_birthday_stamp, is_today_husband = get_birthday_timestamp(friend_dict.get('husband_birthday'))
    birthday_msg = {'wife_birthday_interval': -cal_days(wife_birthday_stamp),
                    'is_today_wife': is_today_wife,
                    'husband_birthday_interval': -cal_days(husband_birthday_stamp),
                    'is_today_husband': is_today_husband}

    # 结尾语句
    sweet_words = friend_dict.get('sweet_words')

    # 获取一句话留言
    dictum_msg = getword()

    # 获取当天的信息，包括天气信息与在一起时长信息
    weather_msg = getWeather(city_name, start_date, love_date)

    # 组成完整的一段话
    today_mess = generate_all_msg(weather_msg, dictum_msg, sweet_words, birthday_msg)

    # print(f'给 {wechat_name} 发送的内容是:\n{today_mess}')

    if IS_WECHAT:
        # 调用接口向指定好友发送
        wechat = Wechat()
        if wechat.isonline(auto_login=True):
            name_uuid = wechat.getfriend().get("name_uuid")
            itchat.send(today_mess, name_uuid)
        time.sleep(5)
        print('微信消息发送成功！')

    if IS_EMAIL:
        send_email(today_mess)

